package com.springboot.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.springboot.constant.WxUserExecl;
import com.springboot.dto.WxUserInfoDTO;
import com.springboot.enums.ErrorEnum;
import com.springboot.enums.WxUserRole;
import com.springboot.exception.MyException;
import com.springboot.service.WxUserService;
import com.springboot.utils.Response;
import com.springboot.vo.PageVO;
import com.springboot.vo.WxUserLoginVO;
import com.springboot.vo.WxUserVO;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * @author: lzh
 */
@RestController
public class WxUserController {

    @Autowired
    WxUserService wxUserService;

    @Autowired
    WxMaService wxMaService;


    /**
     * @param code :
     * @return : com.springboot.utils.Response
     * @descrition: 微信登录
     */
    @GetMapping("/wx/login")
    public Response wxLogin(@RequestParam String code) {
        WxMaJscode2SessionResult sessionInfo = null;
        //根据code从微信获得登录态
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new MyException(ErrorEnum.WX_USER_LOGIN_ERROR);
        }
        //根据openid生成token返回
        WxUserLoginVO wxUserLoginVO = wxUserService.wxLogin(sessionInfo.getOpenid());
        return Response.success(wxUserLoginVO);

    }

    /**
     * @param code          :
     * @param encryptedData :
     * @param iv            :
     * @return : com.springboot.utils.Response
     * @descrition: 微信注册
     */
    @PostMapping("/wx/register")
    public Response register(@RequestParam String code,
                             @RequestParam String encryptedData,
                             @RequestParam String iv) {
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new MyException(ErrorEnum.WX_USER_LOGIN_ERROR);
        }
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionInfo.getSessionKey(), encryptedData, iv);
        WxUserLoginVO wxUserLoginVO = wxUserService.wxRegister(userInfo);
        return Response.success(wxUserLoginVO);
    }

    /**
     * @param wxUserInfoDTO :
     * @return : com.springboot.utils.Response
     * @descrition: 保存/修改用户个人信息
     */
    @PostMapping("/wx/user")
    public Response saveWxUserInfo(WxUserInfoDTO wxUserInfoDTO) {
        wxUserService.saveWxUserInfo(wxUserInfoDTO);
        return Response.success();
    }


    /**
     * @return : com.springboot.utils.Response
     * @descrition: 用户获取个人信息
     */
    @GetMapping("/wx/user")
    public Response getWxUserInfo() {
        WxUserVO wxUserVO = wxUserService.getWxUserInfo();
        return Response.success(wxUserVO);
    }

    /**
     * @return : com.springboot.utils.Response
     * @descrition: 获取用户信息生成二维码
     */
    @GetMapping("/wx/user/qrcode")
    public Response createQrCode() {
        byte[] qrCode = wxUserService.createQrCode();
        return Response.success(qrCode);
    }

    /**
     * @param pageNum    :
     * @param pageSize   :
     * @param keywords   :
     * @param wxUserRole :
     * @return : com.springboot.utils.Response
     * @descrition: 后台获取用户列表
     */
    @GetMapping("/admin/user")
    public Response getWxUserList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                  @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                  @RequestParam(required = false) String keywords,
                                  @RequestParam(required = false) WxUserRole wxUserRole) {
        PageVO pageVO = wxUserService.getWxUserList(pageNum, pageSize, keywords, wxUserRole);
        return Response.success(pageVO);
    }

    /**
     * @param id :
     * @return : com.springboot.utils.Response
     * @descrition: 后台设置检查人员
     */
    @PutMapping("/admin/user/prosecutor")
    public Response setProsecutor(@RequestParam Integer id) {
        wxUserService.setProsecutor(id);
        return Response.success();
    }

    /**
     * @param id :
     * @return : com.springboot.utils.Response
     * @descrition: 后台设置锁定账号
     */
    @PutMapping("/admin/user/lock")
    public Response setLock(@RequestParam Integer id) {
        wxUserService.setLock(id);
        return Response.success();
    }

    /**
     * @param response :
     * @return : void
     * @descrition: 后台用户列表导出execl
     */
    @GetMapping("/admin/user/execl")
    public void dowloadExecl(HttpServletResponse response) {
        HSSFWorkbook wb = wxUserService.dowloadExecl();
        try {
            //设置Http响应头告诉浏览器下载这个附件
            response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(WxUserExecl.SHEETNAME, "utf-8") + ".xls");
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MyException(ErrorEnum.DOWLOAD_EXECL_ERROR);
        }
    }
}
